<?php
class HanghoabhldsController extends AppController {

	var $name = 'Hanghoabhlds';

	function index() {
		$this->Hanghoabhld->recursive = 0;
		$this->set('hanghoabhlds', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid hanghoabhld', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('hanghoabhld', $this->Hanghoabhld->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$hanghoa = $this->data['Hanghoabhld']['hanghoa'];

			$hanghoas = $this->Hanghoabhld->Hanghoa->find('list',array('conditions'=>array('id'=>$hanghoa),
																	'fields'=>array('id','tenhh')));
			
			foreach ($hanghoas as $keyhh => $valuehh)
			{
				$record['Hanghoabhld']['hanghoa_id'] = $keyhh;
				$record['Hanghoabhld']['tenhh'] = $valuehh;
				
				if ($this->Hanghoabhld->saveAll($record)) 
				{
					$this->Session->setFlash(__('Đã thêm vào hàng hóa BHLĐ', true));
				}
				else {
					$this->Session->setFlash(__('Không thể thêm. vui lòng thử lại', true));
				}
			}
			$this->redirect(array('action' => 'index'));
		}
		$hanghoabhld = $this->Hanghoabhld->find('list',array('fields'=>array('hanghoa_id')));
		$hanghoas = $this->Hanghoabhld->Hanghoa->find('list',array('conditions'=>array('NOT'=>array(array('id'=>$hanghoabhld)))));
		$this->set(compact('hanghoas'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid hanghoabhld', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Hanghoabhld->save($this->data)) {
				$this->Session->setFlash(__('The hanghoabhld has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The hanghoabhld could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Hanghoabhld->read(null, $id);
		}
		$hanghoas = $this->Hanghoabhld->Hanghoa->find('list');
		$this->set(compact('hanghoas'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for hanghoabhld', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Hanghoabhld->delete($id)) {
			$this->Session->setFlash(__('Hanghoabhld deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Hanghoabhld was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}
